﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using T3K.SketchEditor.Core;

namespace T3K.SketchEditor.Plugins {
    public partial class NewSketchForm : Form {

        private Project _project;

        public Project Project {
            get { return _project; }
            set { _project = value; }
        }

        public NewSketchForm() {
            InitializeComponent();
            txtSketchAuthor.Text = System.Environment.UserName;
        }

        private void btnCreate_Click(object sender, EventArgs e) {

            errorProvider.SetError(txtSketchName, string.Empty);
            errorProvider.SetError(txtSketchLocation, string.Empty);

            if (string.IsNullOrEmpty(txtSketchName.Text)) {
                errorProvider.SetError(txtSketchName, "The Sketch must have a name.");
                return;
            }

            if (string.IsNullOrEmpty(txtSketchLocation.Text)) {
                errorProvider.SetError(txtSketchLocation, "Please enter a location in your hard drive.");
                return;
            }

            DirectoryInfo dInfo = new DirectoryInfo(txtSketchLocation.Text);

            if (!dInfo.Exists) {
                errorProvider.SetError(txtSketchLocation, "The location does not exist.");
                return;
            }

            DirectoryInfo projectDirectory;

            try {
                projectDirectory = dInfo.CreateSubdirectory(txtSketchName.Text);
            } catch (Exception ex) {
                errorProvider.SetError(txtSketchLocation, ex.Message);
                return;
            }

            Project p = new Project();

            Dictionary<string, string> defaultVars = GetDefaultVars();

            foreach (string var in defaultVars.Keys)
                p[var] = defaultVars[var];

            p["AppPath"] = System.IO.Directory.GetCurrentDirectory().Replace('\\', '/');

            p.ProjectName = string.Format("{0}.skt", txtSketchName.Text);
            p.ProjectFilePath = Path.Combine(projectDirectory.FullName, p.ProjectName);

            p.AddNode("Include.inc", Project.ProjectNodeType.Include);
            p.AddNode(string.Format("{0}.cpp", txtSketchName.Text), Project.ProjectNodeType.CodeFile);
            p.AddNode(string.Format("{0}.h", txtSketchName.Text), Project.ProjectNodeType.HeaderFile);

            Dictionary<string, object> vars = new Dictionary<string, object>();
            vars.Add("ProjectName", txtSketchName.Text);
            vars.Add("Author", txtSketchAuthor.Text);
            vars.Add("Date", DateTime.Now);

            p.CreateFileFromTemplate("Include.inc", "include", vars);

            p.CreateFileFromTemplate
                (string.Format("{0}.cpp", txtSketchName.Text.Replace(' ', '_')), "project.cpp", vars);

            p.CreateFileFromTemplate
                (string.Format("{0}.h", txtSketchName.Text.Replace(' ', '_')), "project.h", vars);

            _project = p;

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnBrowse_Click(object sender, EventArgs e) {

            folderBrowserDialog.RootFolder = System.Environment.SpecialFolder.MyDocuments;
            folderBrowserDialog.SelectedPath = EditorManager.ProjectsPath;
            folderBrowserDialog.ShowNewFolderButton = true;
            folderBrowserDialog.Description = "Select project folder.";

            if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK) {
                txtSketchLocation.Text = folderBrowserDialog.SelectedPath;
            }

        }

        private Dictionary<string, string> GetDefaultVars() {

            Dictionary<string, string> vars = new Dictionary<string, string>();
            FileInfo fInfo = new FileInfo(Path.Combine(System.IO.Directory.GetCurrentDirectory(), "avrbuilder.vars"));
            int fileType = 0;

            if (fInfo.Exists) {
                StreamReader sr = new StreamReader(fInfo.OpenRead());
                string line = null;
                string lastLine = null;
                string var = null;
                while ((line = sr.ReadLine()) != null) {

                    line = line.Trim();

                    if (line.Length == 0 || line[0] == '#')
                        continue;

                    if (line.EndsWith("\\")) {
                        lastLine = line.Substring(0, line.Length - 1);
                        continue;
                    } else {
                        if (lastLine != null)
                            line = lastLine + line;

                        lastLine = null;
                    }

                    switch (fileType) {
                        case 1:
                            vars[var] += string.Format("{0}{1}", ((vars[var].Trim() == string.Empty) ? string.Empty : "|"), line);
                            break;
                        case 2:
                            string[] tokens1 = line.Split(new char[] { '=' }, 2);
                            if (tokens1.Length > 1)
                                vars[tokens1[0].Trim()] = tokens1[1].Trim();
                            break;
                        case 0:
                            if (line.EndsWith(":")) {
                                fileType = 1;
                                var = line.Substring(0, line.Length - 1).Trim();
                                vars[var] = string.Empty;
                            } else if (line.IndexOf('=') > -1) {
                                fileType = 2;
                                string[] tokens2 = line.Split(new char[] { '=' }, 2);
                                if (tokens2.Length > 1)
                                    vars[tokens2[0].Trim()] = tokens2[1].Trim();
                            }
                            break;
                    }

                }
            }

            return vars;

        }

    }
}
